/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.planning;

import cn.ac.nercis.pes.common.constant.knowledge.TargetApplyClaim;
import cn.ac.nercis.pes.common.constant.knowledge.TargetLevel;
import cn.ac.nercis.pes.common.constant.project.SpecialType;
import cn.ac.nercis.pes.community.component.controls.PesComboBox;
import cn.ac.nercis.pes.community.component.controls.PesTextField;
import cn.ac.nercis.pes.community.component.dialog.*;
import cn.ac.nercis.pes.community.component.spreadsheet.planning.SpecialTargetSheetView;
import cn.ac.nercis.pes.community.controller.base.GlobalEventHandle;
import cn.ac.nercis.pes.community.manager.RealTimeSaveManager;
import cn.ac.nercis.pes.community.mapper.project.SystemTargetViewMapper;
import cn.ac.nercis.pes.community.utils.*;
import cn.ac.nercis.pes.community.views.evaluation.planning.TargetConfirmView;
import cn.ac.nercis.pes.model.dto.target.EditSpecialTargetDTO;
import cn.ac.nercis.pes.model.dto.target.LayerTargetDTO;
import cn.ac.nercis.pes.model.dto.target.SpecialTargetConfigDTO;
import cn.ac.nercis.pes.model.dto.target.SpecialTargetDTO;
import cn.ac.nercis.pes.service.project.SystemTargetService;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.StackPane;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.net.URL;
import java.util.List;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.stream.Stream;

/**
 * 特殊指标管理控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class SpecialTargetController implements Initializable, GlobalEventHandle {
    private static final String TITLE_FORMAT = "%s（特殊指标）";

    @FXML
    private StackPane page;

    @FXML
    private Label titleLbl;
    @FXML
    private Button saveButton;
    @FXML
    private Button backButton;
    @FXML
    private Button addSpecialTargetButton;
    @FXML
    private SpecialTargetSheetView sheetView;

    @FXML
    private StackPane addSpecialTargetBox;
    @FXML
    private PesComboBox specialTypeBox;
    @FXML
    private PesComboBox upLevelBox;

    @FXML
    private PesComboBox unitTargetBox;
    @FXML
    private PesTextField unitTargetTxt;
    @FXML
    private PesComboBox applyClaimBox;
    @FXML
    private TextArea targetDescTxt;
    @FXML
    private TextArea reasonsTxt;

    private final SystemTargetService systemTargetService;
    private final ExecutorService executor;
    private final ObservableList<String> specialTypeList = FXCollections.observableArrayList();
    private final ObservableList<String> upLevelList = FXCollections.observableArrayList();
    private final ObservableList<String> unitTargetList = FXCollections.observableArrayList();
    private final RealTimeSaveManager realTimeSaveManager = new RealTimeSaveManager(this::realTimeSave);

    private String currentSystemId;
    private LayerTargetDTO currentLayerTarget;
    private PageDialog pageDialog;
    private SpecialTargetConfigDTO specialTargetConfig;

    public SpecialTargetController() {
        this.systemTargetService = SpringUtils.getBean(SystemTargetService.class);
        this.executor = SpringUtils.getBean(ExecutorService.class);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        saveButton.setGraphic(IconUtils.getGlyph("save-button-icon","btn-icon"));
        backButton.setGraphic(IconUtils.getGlyph("back-button-icon","btn-icon"));
        addSpecialTargetButton.setGraphic(IconUtils.getGlyph("add-button-icon","btn-icon"));
        this.applyClaimBox.getItems().addAll(TargetApplyClaim.findApplyClaims());
        this.specialTypeBox.setItems(specialTypeList);
        this.upLevelBox.setItems(upLevelList);
        this.unitTargetBox.setItems(unitTargetList);
        this.upLevelBox.managedProperty().bind(upLevelBox.visibleProperty());
        this.unitTargetBox.managedProperty().bind(unitTargetBox.visibleProperty());
        this.unitTargetTxt.managedProperty().bind(unitTargetTxt.visibleProperty());
        this.specialTypeBox.valueProperty().addListener((observableValue, stringSingleSelectionModel, t1) -> changeSpecialType());
        this.upLevelBox.valueProperty().addListener((observableValue, stringSingleSelectionModel, t1) -> changeUplevel());
        this.unitTargetBox.valueProperty().addListener((observableValue, stringSingleSelectionModel, t1) -> changeUnitTarget());
        GuiStore.applyQuickSave(this.page,this::onGlobalSave);
        realTimeSaveManager.listenerSheetChange(this.sheetView);
    }

    public void initializeData(String systemId, LayerTargetDTO layerTarget){
        this.currentSystemId = systemId;
        this.currentLayerTarget = layerTarget;
        this.titleLbl.setText(String.format(TITLE_FORMAT,currentLayerTarget.getName()));
        this.sheetView.initialize(systemId,this::onDeleteSpecialTarget);
        this.querySpecialTarget();
        this.loadConfig();
    }

    @Override
    public void onGlobalSave() {
        LogUtils.info(log, "执行快捷保存操作...");
        this.batchSave(false);
    }

    @FXML
    public void onSave(){
        LogUtils.info(log, "执行保存操作...");
        this.batchSave(false);
    }

    public void realTimeSave(){
        LogUtils.info(log, "执行即时保存操作...");
        this.batchSave(true);
    }

    @FXML
    public void onBack(){
        LogUtils.info(log, "执行返回操作...");
        var targetView = AppStore.getEvaluationView(this.currentSystemId, TargetConfirmView.class);
        if(targetView.getController() instanceof TargetConfirmController controller){
            controller.gotoStandardTarget();
        }
    }

    @FXML
    public void onAddSpecialTarget(){
        pageDialog = PageDialog.builder()
                .withIcon("dialog-add-icon")
                .withTitle("新增特殊指标")
                .withContent(this.addSpecialTargetBox)
                .build();
        this.reasonsTxt.clear();
        this.unitTargetTxt.setText("");
        this.specialTypeBox.getSelectionModel().select(0);
        //弹出新增特殊指标页面
        pageDialog.show(this::saveSpecialTarget);
    }

    private void batchSave(boolean realTime){
        if(!this.sheetView.validate()){
            if(!realTime){
                AppUtils.showMessageDialog("以下标出的特殊指标的必填信息不能为空",MessageType.WARN,this.page);
            }
            return;
        }
        var specialTargets = this.sheetView.getModifyData();
        if (!realTime && CollectionUtils.isEmpty(specialTargets)) {
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.SUCCESS).withMessage("保存成功")
                    .build().show();
            return;
        }
        LogUtils.info(log, "批量保存特殊指标信息...");
        LogUtils.record(log, "请求数据：{}", specialTargets);
        //未保存的数据进行批量保存
        CompletableFuture.supplyAsync(() -> this.systemTargetService.batchSaveSpecialTarget(specialTargets))
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        //更新表数据
                        this.querySpecialTarget();
                        if(!realTime){
                            AppUtils.showMessageDialog("保存成功",MessageType.SUCCESS,this.page);
                        }
                    } else {
                        if(realTime){
                            log.error("即时保存特殊指标信息失败：{}",res.getMsg());
                        }else{
                            AppUtils.showMessageDialog(res.getMsg(),MessageType.FAIL,this.page);
                        }
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("批量保存特殊指标信息出错!", ex);
                    return null;
                });
    }

    private void querySpecialTarget() {
        LogUtils.info(log, "获取特殊指标信息...");
        LogUtils.record(log, "请求数据，systemID:{},layerId:{}", this.currentSystemId,this.currentLayerTarget.getTargetId());
        CompletableFuture.supplyAsync(() -> this.systemTargetService.findUnitSpecialTargets(this.currentSystemId, this.currentLayerTarget.getTargetId()))
                .thenAccept(res -> Platform.runLater(() -> {
                    var data = res.stream()
                            .map(SystemTargetViewMapper.INSTANCE::toUnitSpecialTargetVO)
                            .toList();
                    this.sheetView.loadContent(data);
                }))
                .exceptionally((ex) -> {
                    log.error("获取密码服务信息出错!", ex);
                    return null;
                });
    }

    private void onDeleteSpecialTarget(Set<String> ids){
        LogUtils.info(log, "执行删除操作...");
        if(CollectionUtils.isEmpty(ids)){
            return;
        }
        AlertDialog alertDialog = AlertDialog.builder()
                .withMode(AlertMode.CONFIRM)
                .withType(AlertType.WARN)
                .withTitle("删除提示")
                .withContent("确认删除当前特殊指标信息吗？")
                .withContainer(this.page)
                .build();
        alertDialog.show((confirm)->{
            if(!confirm){
                return;
            }
            deleteSpecialTarget(ids);
        });
    }

    private void deleteSpecialTarget(final Set<String> ids) {
        LogUtils.info(log, "删除特殊指标信息...");
        LogUtils.info(log, "请求数据：{}", ids);
        CompletableFuture.supplyAsync(() -> this.systemTargetService.batchDeleteSpecialTarget(ids))
                .thenAccept(res -> Platform.runLater(() -> {
                    if (res.isSuccess()) {
                        //更新表数据
                        this.querySpecialTarget();
                        MessageDialog.builder()
                                .withContainer(this.page)
                                .withType(MessageType.SUCCESS).withMessage("删除成功")
                                .build().show();
                    } else {
                        MessageDialog.builder()
                                .withContainer(this.page)
                                .withType(MessageType.FAIL).withMessage(res.getMsg())
                                .build().show();
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("删除特殊指标信息出错!", ex);
                    return null;
                });
    }

    private void saveSpecialTarget(){
        var specialType = SpecialType.fromName(specialTypeBox.getValue());
        if(specialType==SpecialType.CUSTOM && StringUtils.isBlank(unitTargetTxt.getText())){
            return;
        }
        var specialData = EditSpecialTargetDTO.builder()
                .systemId(this.currentSystemId)
                .layerTargetId(currentLayerTarget.getTargetId())
                .specialType(SpecialType.fromName(specialTypeBox.getValue()))
                .targetDesc(StringUtils.trim(targetDescTxt.getText()))
                .reasons(StringUtils.trim(reasonsTxt.getText()))
                .applyClaim(applyClaimBox.getValue())
                .build();
        if(specialType==SpecialType.CUSTOM){
            specialData.setName(StringUtils.trim(unitTargetTxt.getText()));
        }else{
            specialData.setName(unitTargetBox.getValue());
            var kmTargetId = specialTargetConfig.getUpgrades()
                    .stream()
                    .filter(st->StringUtils.equals(st.getName(),unitTargetBox.getValue()))
                    .map(SpecialTargetDTO::getId)
                    .findFirst()
                    .orElse(StringUtils.EMPTY);
            specialData.setKmTargetId(kmTargetId);
        }
        LogUtils.info(log, "保存新增特殊指标信息...");
        LogUtils.record(log, "请求数据:{}", specialData);
        CompletableFuture.supplyAsync(() -> this.systemTargetService.saveSpecialTarget(specialData),this.executor)
                .thenAccept(res->Platform.runLater(()->{
                    if(res.isSuccess()){
                        this.pageDialog.close();
                        this.querySpecialTarget();
                        AppUtils.showMessageDialog("保存成功",MessageType.SUCCESS,this.page);
                    }else{
                        AppUtils.showMessageDialog(res.getMsg(), MessageType.FAIL, this.addSpecialTargetBox);
                    }
                }))
                .exceptionally((ex) -> {
                    log.error("保存特殊指标信息出错!", ex);
                    return null;
                });
    }

    private void loadConfig(){
        this.specialTypeList.clear();
        this.unitTargetList.clear();
        CompletableFuture.supplyAsync(() -> this.systemTargetService.getSpecialTargetConfig(this.currentSystemId,
                currentLayerTarget.getTargetId()),this.executor)
                .thenAccept(res-> Platform.runLater(()->this.initConfigData(res)))
                .exceptionally((ex) -> {
                    log.error("获取单元特殊指标信息出错!", ex);
                    MessageDialog.builder()
                            .withContainer(this.page)
                            .withType(MessageType.FAIL)
                            .withMessage("加载数据表内容失败！")
                            .build().show();
                    return null;
                });
    }

    private void initConfigData(SpecialTargetConfigDTO config){
        this.specialTargetConfig = config;
        if(CollectionUtils.isEmpty(config.getUpgrades()) || CollectionUtils.isEmpty(config.getSources())){
            this.specialTypeList.add(SpecialType.CUSTOM.getName());
            return;
        }
        var upgradeTargets = config.getSources()
                .stream()
                .map(SpecialTargetDTO::getName)
                .filter(itemName->config.getUpgrades().stream().anyMatch(upgrade->StringUtils.equals(itemName,upgrade.getName())))
                .toList();
        var uplevelTargets = config.getUpgrades()
                .stream()
                .map(SpecialTargetDTO::getName)
                .filter(itemName->config.getSources().stream().noneMatch(source->StringUtils.equals(itemName,source.getName())))
                .toList();
        if(CollectionUtils.isNotEmpty(upgradeTargets) && CollectionUtils.isNotEmpty(uplevelTargets)){
            this.specialTypeList.addAll(Stream.of(SpecialType.UPGRADE,SpecialType.UPLEVEL,SpecialType.CUSTOM)
                    .map(SpecialType::getName).toList());
        }else if(CollectionUtils.isNotEmpty(upgradeTargets)){
            this.specialTypeList.addAll(Stream.of(SpecialType.UPGRADE,SpecialType.CUSTOM).map(SpecialType::getName).toList());
        }else if(CollectionUtils.isNotEmpty(uplevelTargets)){
            this.specialTypeList.addAll(Stream.of(SpecialType.UPLEVEL,SpecialType.CUSTOM).map(SpecialType::getName).toList());
        }
        this.specialTypeBox.getSelectionModel().select(0);
    }

    private List<String> findUpgradeTargets(TargetLevel upLevel){
        return specialTargetConfig.getSources()
                .stream()
                .map(SpecialTargetDTO::getName)
                .filter(name -> specialTargetConfig.getUpgrades().stream().anyMatch(upgrade-> upgrade.getLevel() == upLevel && StringUtils.equals(name,upgrade.getName())))
                .toList();
    }

    private List<String> findUplevelTargets(TargetLevel upLevel){
        return specialTargetConfig.getUpgrades()
                .stream()
                .filter(st->st.getLevel() == upLevel && specialTargetConfig.getSources().stream().noneMatch(source-> StringUtils.equals(st.getName(),source.getName())))
                .map(SpecialTargetDTO::getName)
                .toList();
    }

    private void clearAddSpecialTarget(){
        this.targetDescTxt.clear();
        this.reasonsTxt.clear();
        this.unitTargetTxt.setText("");
    }

    private void changeSpecialType(){
        var selectedItem = this.specialTypeBox.getSelectionModel().getSelectedItem();
        if(StringUtils.isBlank(selectedItem)){
            return;
        }
        var specialType = SpecialType.fromName(selectedItem);
        if(specialType == SpecialType.CUSTOM){
            this.upLevelBox.setVisible(false);
            this.unitTargetBox.setVisible(false);
            this.applyClaimBox.setDisable(false);
            this.unitTargetTxt.setVisible(true);
            this.targetDescTxt.setEditable(true);
            this.clearAddSpecialTarget();
        }else{
            this.unitTargetTxt.setVisible(false);
            this.targetDescTxt.setEditable(false);
            this.upLevelBox.setVisible(true);
            this.unitTargetBox.setVisible(true);
            this.applyClaimBox.setDisable(true);
            this.upLevelList.clear();
            if(specialType == SpecialType.UPGRADE){
                this.upLevelList.addAll(specialTargetConfig.getUpLevels()
                        .stream()
                        .filter(upLevel->CollectionUtils.isNotEmpty(findUpgradeTargets(upLevel)))
                        .map(TargetLevel::getName).toList());
            }else{
                this.upLevelList.addAll(specialTargetConfig.getUpLevels()
                        .stream()
                        .filter(upLevel->CollectionUtils.isNotEmpty(findUplevelTargets(upLevel)))
                        .map(TargetLevel::getName).toList());
            }
            this.upLevelBox.getSelectionModel().select(0);
        }
    }

    private void changeUplevel(){
        var specialType = SpecialType.fromName(this.specialTypeBox.getSelectionModel().getSelectedItem());
        var upLevel = TargetLevel.fromName(this.upLevelBox.getSelectionModel().getSelectedItem());
        this.unitTargetList.clear();
        if(specialType == SpecialType.UPGRADE){
            this.unitTargetList.addAll(this.findUpgradeTargets(upLevel));
        }else{
            this.unitTargetList.addAll(this.findUplevelTargets(upLevel));
        }
        this.unitTargetBox.getSelectionModel().select(0);
    }

    private void changeUnitTarget(){
        var specialType = SpecialType.fromName(this.specialTypeBox.getSelectionModel().getSelectedItem());
        var upLevel = TargetLevel.fromName(this.upLevelBox.getSelectionModel().getSelectedItem());
        if(specialType == SpecialType.CUSTOM){
            return;
        }
        var selectItem = this.unitTargetBox.getSelectionModel().getSelectedItem();
        var unitTarget = specialTargetConfig.getUpgrades()
                .stream()
                .filter(st -> StringUtils.equals(st.getName(), selectItem) && st.getLevel() == upLevel)
                .findFirst()
                .orElse(null);
        if(Objects.nonNull(unitTarget)){
            this.applyClaimBox.getSelectionModel().select(unitTarget.getApplyClaim());
            this.targetDescTxt.setText(unitTarget.getTargetDesc());
        }
    }
}